package com.zeen.wima.update;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.util.Log;

import com.zeen.wima.common.Workspace;

public class DownloadTask extends AsyncTask<String, Integer, String> {

	private AppInfo taskInfo;

	public AppInfo getInfo() {
		return taskInfo;
	}

	private boolean excuted = false;

	public interface PluginView {
		void onProgressUpdate(int values);

		void onDownloadFinished(String path);
	}

	private PluginView view;

	public void setView(PluginView v) {
		view = v;
	}

	public DownloadTask(AppInfo info) {
		taskInfo = info;
	}

	public boolean hasDownloaded() {
		return excuted;
	}

	public String getSetupPath() {
		return taskInfo.getSetupPath();
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		if (view != null)
			view.onProgressUpdate(values[0]);
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if (view != null)
			view.onDownloadFinished(result);
	}

	@Override
	protected String doInBackground(String... params) {
		String path = "";
		try {
			URL imageUrl = new URL(taskInfo.getUrl());
			URLConnection connection = (HttpURLConnection) imageUrl
					.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(input);
			File f = new File(Workspace.getDownloadDir() + "/"
					+ taskInfo.getName() + ".apk");
			FileOutputStream os = new FileOutputStream(f);
			byte[] buff = new byte[1024 * 800];
			int count = -1;
			int loadedBytes = 0;
			while ((count = bis.read(buff)) != -1) {
				os.write(buff, 0, count);
				loadedBytes += count;
				publishProgress(loadedBytes);
			}
			os.flush();
			os.close();
			input.close();
			path = f.getAbsolutePath();
			taskInfo.setSetupPath(path);
		} catch (Exception e) {
			Log.e("download", e.getMessage());
		}
		return path;
	}

	public void download() {
		excuted = true;
		this.execute(null);
	}
}
